// 定义树节点类
export class TreeNode<T> {
    /**
     * 当前树节点的值
     */
    private _value: T;
    get value(): T {
        return this._value;
    }
    /**
     * 父节点,根节点为null
     */
    private _parent: TreeNode<T> = null;
    get parent(): TreeNode<T> {
        return this._parent;
    }

    /**
     * 子节点
     */
    private _children: TreeNode<T>[] = [];
    get children(): TreeNode<T>[] {
        return this._children;
    }

    constructor(value: T) {
        this._value = value;
    }

    /**
     * 添加子节点
     * @param node 
     */
    add(child: TreeNode<T>): void {
        child._parent = this; // 设置子节点的父节点
        this._children.push(child);
    }

    /**
     * 获取子节点（递归查找）
     * @param callback 
     */
    get(callback: (value: T) => boolean): TreeNode<T> | null {
        if (callback(this.value)) return this;
        for (const child of this.children) {
            const result = child.get(callback);
            if (result) return result;
        }
        return null;
    }

    /**
     * 某一个节点是否满足条件
     * @param callback 
     * @returns 
     */
    some(callback: (value: T) => boolean): boolean {
        if (callback(this.value)) return true;
        return this.children.some(child => child.some(callback));
    }

    /**
     * 是否所有节点满足条件
     * @param callback 
     * @returns 
     */
    every(callback: (value: T) => boolean): boolean {
        if (!callback(this.value)) return false;
        return this.children.every(child => child.every(callback));
    }

    /**
     * 前序遍历树的方法
     * @param callback 
     */
    traverse(callback: (value: T) => void): void {
        callback(this.value);
        this.children.forEach(child => child.traverse(callback));
    }

    /**
     * 删除子节点
     * @param child 
     */
    removeChild(child: TreeNode<T>): boolean {
        const index = this._children.indexOf(child);
        if (index !== -1) {
            this._children.splice(index, 1);
            child._parent = null; // 清除子节点的父节点引用
            return true;
        }
        return false;
    }
}

/**
 * 一个简单的树结构
 */
export class Tree<T> extends TreeNode<T> {
    
}